package com.find.answer.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.find.answer.domain.dto.PageDto;
import com.find.answer.domain.http.Result;
import com.find.answer.domain.po.Employee;
import com.find.answer.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author Seon
 * @date 2022/10/13 16:17
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    private static final int EMPLOYEE_STATUS_BANED = 0;

    private static final String EMPLOYEE = "employee";

    private static final String DEFAULT_PASSWORD = "123456";

    @PostMapping("/login")
    public Result<?> login(@RequestBody Employee employee,
                           HttpServletRequest request) {

        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("username", employee.getUsername());
        Employee queryRes = employeeService.getOne(wrapper);

        if (queryRes == null) {
            return Result.error("用户名不存在");
        } else {
            if (queryRes.getStatus() == EMPLOYEE_STATUS_BANED) {
                return Result.error("用户已被禁用");
            } else if (queryRes.getPassword().equals(password)) {
                HttpSession session = request.getSession();
                session.setAttribute(EMPLOYEE, queryRes.getId());
                return Result.success(queryRes);
            } else {
                return Result.error("密码错误");
            }
        }
    }

    @PostMapping("/logout")
    public Result<?> logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute(EMPLOYEE);
        return Result.success(null);
    }

    @PostMapping("")
    public Result<?> addEmployee(@RequestBody Employee employee) {
        /*
        一开始的密码就设置为123456，后期员工自己登录上来的时候再自行修改。
         */
        String defaultPassword = DigestUtils.md5DigestAsHex(DEFAULT_PASSWORD.getBytes());
        /*
         * 现在id只能手动设置，后期把session的登录机制改为springsecurity的方式来进行认证
         * 然后id的的数据就从ContextHolder里面取得，放到自动填充里面，这样子MetaObjectHandler
         * 就可以自动填充createBy和updateBy了。
         */
        employee.setPassword(defaultPassword);
        boolean save = employeeService.save(employee);
        if (!save) {
            return Result.error("添加员工失败");
        }
        return Result.success("添加成功");
        //    19150931615  620503200210150313  测试数据
    }
    @GetMapping("/page")
    public Result<?> getEmployeePage(PageDto pageDto,
                                     @RequestParam(value = "name",required = false) String name) {
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name),"name", name);
        wrapper.orderByDesc("update_time");
        IPage<Employee> page = new Page<>(pageDto.getPage(), pageDto.getPageSize());

        try {
            employeeService.page(page, wrapper);
            return Result.success(page);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("接口异常");
    }

    @GetMapping("/{employeeId}")
    public Result<?> getEmployeeById(@PathVariable("employeeId") Integer id) {
        Employee employee = employeeService.getById(id);
        if (employee == null) {
            return Result.error("用户不存在");
        }
        return Result.success(employee);
    }

    @PutMapping("")
    public Result<?> updateEmployee(@RequestBody Employee employee) {
        boolean save = employeeService.updateById(employee);
        if (!save) {
            return Result.error("更新失败");
        }
        return Result.success("用户信息修改成功");
    }

}
